/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package fr.uniscol.service.impl;

import fr.uniscol.dao.IAdminBasesDao;
import fr.uniscol.dao.IEtablissementDao;
import fr.uniscol.dao.IUtilisateurDao;
import fr.uniscol.model.BaseAnneeScolaire;
import fr.uniscol.model.IUniscolUser;
import fr.uniscol.service.IAdminBasesService;
import fr.uniscol.service.IUtilisateurService;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 *
 * @author Christophe
 */
@Service("adminBasesService")
public class AdminBasesServiceImpl implements IAdminBasesService {

    @Autowired
    private IAdminBasesDao adminBasesDao;
    
    @Autowired
    private IEtablissementDao etablissementDao;
    
    @Autowired
    private IUtilisateurDao utilisateurDao;
    
    @Override
    public List<BaseAnneeScolaire> getAllBases() {
        return adminBasesDao.getAllBases();
    }

    @Override
    @Transactional(readOnly = false)
    public boolean saveBase(BaseAnneeScolaire base) {
        long etabId = 0;
        if(base.getEtablissement() != null){
            etabId = etablissementDao.saveEtablissement(base.getEtablissement());
            base.getEtablissement().setId(etabId);
        }
        
        long baseId = adminBasesDao.saveBase(base);
        
        if(base.getAdministrateur() != null){
            long userId = base.getAdministrateur().getId();
            
            utilisateurDao.saveUser(base.getAdministrateur());
            
            if(userId == 0){
                baseId = adminBasesDao.saveBase(base);
            }
        }
        
        return baseId > 0;
    }

    @Override
    @Transactional(readOnly = true)
    public BaseAnneeScolaire getBaseById(long baseId) {
        BaseAnneeScolaire base = adminBasesDao.getBaseById(baseId);
        
        // Les utilisateurs
        base.setUtilisateurs(utilisateurDao.getAllUtilisateurOfEtablissement(base));
        
        return base;
    }

    @Override
    @Transactional(readOnly = false)
    public boolean deleteBase(BaseAnneeScolaire base) {
        
        // Supprime tous 
        
        boolean ret = adminBasesDao.deleteBase(base);
        
        return ret;
    }
    
}
